import fs from "fs-extra";
import { toolchain } from "../toolchain.js";
import { SVNClient } from "@taiyosen/easy-svn";
import moment from "moment";

export class SVN {
    private readonly lcdMap: Record<string, string> = {};
    private svn: SVNClient;

    constructor() {
        this.svn = new SVNClient();
        this.svn.setConfig({ silent: true });
    }

    async loadCache(): Promise<void> {
        const cacheFile = `tmp/${toolchain.opts.projectName}.svn.txt`;
        if (fs.existsSync(cacheFile)) {
            const cacheContent = await fs.readFile(cacheFile, 'utf-8');
            const lines = cacheContent.split(/\r?\n/);
            lines.forEach(v => {
                const [file, lcd] = v.split(',');
                this.lcdMap[file] = lcd;
            })
        }
    }

    async isModifiedRecent(file: string, days: number): Promise<{ result: boolean, date?: string }> {
        const date = await this.getLastChangedDate(file);
        if (date != null) {
            return { result: moment().diff(moment(date), 'd') < days, date };
        } else {
            console.error('could not fetch last changed date for: ' + file);
            return { result: false };
        }
    }

    async getLastChangedDate(file: string): Promise<string | null> {
        const info = await this.svn.info([file], { revision: 'BASE' });
        const dateMch = info.match(/Last Changed Date: (\S+)/);
        if (dateMch != null) {
            const date = dateMch[1];
            this.lcdMap[file] = date;
            return date;
        }
        return null;
    }

    async save(): Promise<void> {
        const cacheFile = `tmp/${toolchain.opts.projectName}.svn.txt`;
        const files = Object.keys(this.lcdMap);
        files.sort();
        await fs.writeFile(cacheFile, files.map(v => v + ',' + this.lcdMap[v]).join('\n'), 'utf-8');
    }
}
